package cool.taomu.toolkit.demo.stock.controller

import cool.taomu.toolkit.Context
import cool.taomu.toolkit.demo.stock.SignalHandler
import cool.taomu.toolkit.demo.stock.SignalUtils
import cool.taomu.toolkit.demo.stock.entity.StockHistory
import cool.taomu.toolkit.demo.stock.service.DeviationService
import cool.taomu.toolkit.stock.dao.jooq.enums.TaomuStockSignalSignalType
import cool.taomu.toolkit.stock.dao.jooq.tables.TaomuStockHistory
import cool.taomu.toolkit.stock.dao.jooq.tables.TaomuStockSignal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import javax.inject.Inject
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.core.Response
import org.jooq.DSLContext
import org.slf4j.LoggerFactory

@Path("stock")
class StockController {

	val static LOG = LoggerFactory.getLogger(StockController);

	@Inject
	DSLContext dsl;

	@Inject
	Context context;

	@GET
	@Path("/signal/{xdays}/{code}")
	def signal(@PathParam("xdays") Integer xDays, @PathParam("code") String code) {
		LOG.info("******计算股票买卖信号******:{}", code)
		context.executor.execute([
			var ncode = code
			if (code.startsWith("60")) {
				ncode = "sh." + code;
			} else if (code.startsWith("00")) {
				ncode = "sz." + code;
			}

			val endDate = LocalDateTime.now().toLocalDate().atStartOfDay();
			val startDate = endDate.minus(xDays, ChronoUnit.DAYS).toLocalDate().atStartOfDay();
			var stockHistorylist = dsl.selectFrom(TaomuStockHistory.TAOMU_STOCK_HISTORY).where(
				TaomuStockHistory.TAOMU_STOCK_HISTORY.CODE.eq(ncode)).and(
				TaomuStockHistory.TAOMU_STOCK_HISTORY.DATE.greaterOrEqual(startDate)
			).and(TaomuStockHistory.TAOMU_STOCK_HISTORY.DATE.lessOrEqual(endDate)).orderBy(
				TaomuStockHistory.TAOMU_STOCK_HISTORY.DATE.asc()).fetchInto(StockHistory)

			SignalUtils.detectSignals(ncode, stockHistorylist, new SignalHandler() {
				override onSignal(String stockCode, LocalDate date, String signalType, String indicator) {
					LOG.info("*****插入信号*******:{},{}", date, stockCode)
					dsl.insertInto(TaomuStockSignal.TAOMU_STOCK_SIGNAL).set(
						TaomuStockSignal.TAOMU_STOCK_SIGNAL.STOCK_CODE, stockCode).set(
						TaomuStockSignal.TAOMU_STOCK_SIGNAL.SIGNAL_DATE, date).set(
						TaomuStockSignal.TAOMU_STOCK_SIGNAL.SIGNAL_TYPE,
						TaomuStockSignalSignalType.valueOf(signalType)).set(
						TaomuStockSignal.TAOMU_STOCK_SIGNAL.INDICATOR, indicator).execute();
				}
			})
			LOG.info("*****计算结束*******:{}", code)
		])
		return Response.accepted().build();
	}

	@Inject
	DeviationService service

	@GET
	@Path("/signal/deviation/{xdays}/{code}")
	def signal2(@PathParam("xdays") Integer xDays, @PathParam("code") String code) {
		LOG.info("******计算股票买卖信号******:{}", code)
		context.executor.execute([
			service.deviationEvel(xDays, code)
		// LOG.info("*****计算结束*******:{}", code)
		])
		return Response.accepted().build();
	}
}
